package b1.mobile.blackberry.screen;

import java.util.Vector;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.table.DataTemplate;
import net.rim.device.api.ui.component.table.TableController;
import net.rim.device.api.ui.component.table.TableView;
import net.rim.device.api.ui.component.table.TemplateColumnProperties;
import net.rim.device.api.ui.component.table.TemplateRowProperties;
import net.rim.device.api.ui.container.FlowFieldManager;
import net.rim.device.api.ui.container.GridFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.BackgroundFactory;
import b1.mobile.blackberry.dao.DataAccessDelegate;
import b1.mobile.blackberry.dao.KPIDAO;
import b1.mobile.blackberry.entity.KPIEntity;
import b1.mobile.blackberry.entity.TodoEntity;
import b1.mobile.blackberry.io.http.ResponseParserHelper;
import b1.mobile.blackberry.io.http.Serviceworker;
import b1.mobile.blackberry.io.http.Serviceworker.ServiceDelegate;
import b1.mobile.blackberry.io.http.SoapContentProvider;
import b1.mobile.blackberry.lang.CommonConstant;
import b1.mobile.blackberry.ui.component.IconListField;
import b1.mobile.blackberry.ui.component.KPITableModel;
import b1.mobile.blackberry.ui.component.TabField;
import b1.mobile.blackberry.ui.component.TabPanel;
import b1.mobile.blackberry.ui.component.util.Capsule;
import b1.mobile.blackberry.ui.component.util.FieldFactory;
import b1.mobile.blackberry.ui.component.util.FontFactory;
import b1.mobile.blackberry.ui.component.util.ThemeUtil;
import b1.mobile.blackberry.controller.AgentController;

public class HomeScreen extends BaseFunctionScreen implements ServiceDelegate, DataAccessDelegate {

	private TabPanel tabPanel;
	private VerticalFieldManager functionFieldManager;
	private Manager todoListFieldManager;
	private IconListField todoList;

	private KPITableModel theKPIModel;
	private Manager keyIndMgr;

	public HomeScreen() {
		super(NO_VERTICAL_SCROLL | USE_ALL_WIDTH);
		
		setTitle(FieldFactory.makeScreenTitle("Home"));
		ThemeUtil.decorateScreen(this);

		tabPanel = new TabPanel();
		tabPanel.setCount(4);
		tabPanel.setPadding(6, 6, 6, 6);
		footFieldManager.add(tabPanel);
		this.setStatus(footFieldManager);

		tabPanel.addTab(Bitmap.getBitmapResource("tab-icon-01-approval.png"), "Approval");
		tabPanel.addTab(Bitmap.getBitmapResource("tab-icon-02-bp.png"), "BP");
		tabPanel.addTab(Bitmap.getBitmapResource("tab-icon-03-report.png"), "Report");
		tabPanel.addTab(Bitmap.getBitmapResource("tab-icon-04-stock.png"), "Stock");

		/*
		 * To-do List START
		 */
		functionFieldManager = new VerticalFieldManager(VERTICAL_SCROLL | VERTICAL_SCROLLBAR
				| USE_ALL_WIDTH);
		this.add(functionFieldManager);
		
		functionFieldManager.add(FieldFactory.makeGroupTitle("To-do List"));
		todoListFieldManager = new VerticalFieldManager();
		todoListFieldManager.setBackground(BackgroundFactory.createSolidBackground(0x00F3F3F3));
		
		todoList = new IconListField();
		todoList.setRowHeight((int) (todoList.getRowHeight() * 2.5));
		todoListFieldManager.add(todoList);
		functionFieldManager.add(todoListFieldManager);
	}

	protected void onUiEngineAttached(boolean attached) {
		if (attached) {
			tabPanel.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					if (context == 6789016
							&& tabPanel.getFieldWithFocus() instanceof TabField) {
						TabField tabField = (TabField) tabPanel
								.getFieldWithFocus();
						int selectIndex = tabField.getFieldIndex();

						switch (selectIndex) {
						case 0:
							onApprovalList();
							break;
						case 1:
							onBP();
							break;
						case 2:
							onReports();
							break;
						case 3:
							onStock();
							break;
						default:
							break;
						}
					}
				}
			});
			
			onLoadToDoList(null);
			KPIDAO kdao = new KPIDAO(this);
			kdao.list();
		}
	}

	protected boolean navigationClick(int status, int time) {
		if (getLeafFieldWithFocus() instanceof IconListField) {
			if(!todoList.isEmpty()){
				Capsule capsule = (Capsule) todoList.get(todoList,
						todoList.getSelectedIndex());
				Object value = capsule.value;
				if (value instanceof TodoEntity) {
					getUiEngine().pushScreen(
							new ActivityDetailScreen(((TodoEntity) value)
									.getTodoId()));
				}
			}
		} else{
			super.navigationClick(status, time);
		}
		return true;
	}

	protected void onStock() {
		getUiEngine().pushScreen(new StockListScreen());
	}

	protected void onReports() {
		getUiEngine().pushScreen(new ReportListScreen());
	}

	protected void onBP() {
		getUiEngine().pushScreen(new BPListScreen());
	}

	protected void onApprovalList() {
		getUiEngine().pushScreen(new ApprovalListScreen());
	}

	public void onGetResult(Serviceworker worker) {
		if (worker.responseCode == 200) {
			if (worker.getOperator().equals("GetTodoList")) {
				bindTodoList(worker.responseMessage);
			}
		}
	}

	private void bindTodoList(String response) {
		ResponseParserHelper help = new ResponseParserHelper(response);
		JSONArray array = (JSONArray) help.parse("GetTodoListResult");

		Vector items = new Vector();
		for (int i = 0; i < array.length(); i++) {
			try {
				JSONObject jobj = array.getJSONObject(i);
				TodoEntity obj = new TodoEntity();
				String type = jobj.getString("Activity");
				if (type.equals("C")) {
					obj.setTodoCategory(CommonConstant.TODO_CATEGORY_CALL);
				} else if (type.equals("M")) {
					obj.setTodoCategory(CommonConstant.TODO_CATEGORY_METTING);
				} else {
					obj.setTodoCategory(CommonConstant.TODO_CATEGORY_DISCUSS);
				}

				obj.setTodoDate(jobj.getString("StartDateTime"));
				obj.setTodoId(jobj.getString("Number"));
				obj.setTodoName(jobj.getString("Remarks"));

				items.addElement(new Capsule(obj.getTodoName(), obj));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		final Capsule[] capsules = new Capsule[items.size()];
		items.copyInto(capsules);

		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				todoList.set(capsules);
			}
		});
	}

	/*
	 * private void onLoading(){ loadingIcon = new
	 * ProgressAnimationField(Bitmap.getBitmapResource("spinner.png"), 5,
	 * Field.FIELD_HCENTER ); footFieldManager.insert(loadingIcon, 0); }
	 * 
	 * private void onLoadingDone(){ footFieldManager.delete(loadingIcon); }
	 */

	private void onLoadToDoList(Vector allItem) {
		/* TODO: get to-do list from service */
		String[] names = new String[] { "Count" };
		String[] values = new String[] { "3" };
		SoapContentProvider soap = new SoapContentProvider("GetTodoList",
				names, values);

		try {
			Serviceworker worker = new Serviceworker(this,
					AgentController.getServer(), soap);
			new Thread(worker).start();
		} catch (Exception ex) {

		}
	}

	private void bindKPI(Vector vData) {
		/*
		 * KPI START
		 */
		functionFieldManager.add(FieldFactory.makeGroupTitle(resources.getString(LABEL_KEY_INDICATORS)));
		keyIndMgr = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL);
		keyIndMgr.setBackground(BackgroundFactory
				.createSolidBackground(0x00F3F3F3));
		functionFieldManager.add(keyIndMgr);
		
		theKPIModel = new KPITableModel();
		keyIndMgr.add(createKPITableView());
		
		functionFieldManager.add(new LabelField());
		
		for (int i = 0; i < vData.size(); i++) {
			KPIEntity ety = (KPIEntity)vData.elementAt(i);
			theKPIModel.addRow(ety);
		}
	}

	private TableView createKPITableView() {
		TableView theView = new TableView(theKPIModel);
		TableController theController = new TableController(theKPIModel,
				theView);
		theController.setFocusPolicy(TableController.ROW_FOCUS);
		theView.setController(theController);

		DataTemplate theTemplate = new DataTemplate(theView, 1, 1) {
			Font systemFont = FontFactory.getFont(Font.PLAIN, 6, Ui.UNITS_pt);

			public Field[] getDataFields(int modelRowIndex) {
				
				KPIEntity data = (KPIEntity)theKPIModel.getRow(modelRowIndex);		
				
				Manager kMgr = new VerticalFieldManager(USE_ALL_WIDTH);
				if(modelRowIndex > 0)
					kMgr.add(new SeparatorField(USE_ALL_WIDTH));
				
				/*** KPI Head ***/
				Manager rowMgr = new HorizontalFieldManager(USE_ALL_WIDTH);
				rowMgr.setPadding(5, 5, 5, 5);
				
				LabelField title = new LabelField(data.getStringProperty(KPIEntity.JK_HEAD));
				title.setFont(systemFont.derive(Font.BOLD));
				rowMgr.add(title);
				
				LabelField value = new LabelField(data.getStringProperty(KPIEntity.JK_HEADVALUE), USE_ALL_WIDTH | DrawStyle.RIGHT);
				value.setPadding(0, 10, 0, 0);
				value.setFont(systemFont);
				rowMgr.add(value);
				
				kMgr.add(rowMgr);
				
				/*** KPI First ***/
				rowMgr = new HorizontalFieldManager(USE_ALL_WIDTH);
				rowMgr.setPadding(0, 5, 0, 5);
				
				title = new LabelField(data.getStringProperty(KPIEntity.JK_FIRST));
				title.setFont(systemFont);
				title.setPadding(0, 0, 0, 15);
				rowMgr.add(title);
				
				value = new LabelField(data.getStringProperty(KPIEntity.JK_FIRSTVALUE), USE_ALL_WIDTH | DrawStyle.RIGHT);
				value.setPadding(0, 15, 0, 0);
				value.setFont(systemFont);
				rowMgr.add(value);
				
				if(!data.getStringProperty(KPIEntity.JK_FIRST).equals(""))
					kMgr.add(rowMgr);
				
				/*** KPI Second ***/
				rowMgr = new HorizontalFieldManager(USE_ALL_WIDTH);
				rowMgr.setPadding(0, 5, 5, 5);
				
				title = new LabelField(data.getStringProperty(KPIEntity.JK_SECOND));
				title.setFont(systemFont);
				title.setPadding(0, 0, 0, 15);
				rowMgr.add(title);
				
				value = new LabelField(data.getStringProperty(KPIEntity.JK_SECONDVALUE), USE_ALL_WIDTH | DrawStyle.RIGHT);
				value.setPadding(0, 15, 0, 0);
				value.setFont(systemFont);
				rowMgr.add(value);
				
				if(!data.getStringProperty(KPIEntity.JK_SECOND).equals(""))
					kMgr.add(rowMgr);

				return new Field[]{kMgr};
			}

		};

		theTemplate.setRowProperties(0, new TemplateRowProperties(36));

		theTemplate.createRegion(new XYRect(0, 0, 1, 1));
		theTemplate.setColumnProperties(0, new TemplateColumnProperties(95, TemplateColumnProperties.PERCENTAGE_WIDTH));

		theTemplate.useFixedHeight(false);
		theView.setDataTemplate(theTemplate);
		theView.setMargin(0, 0, 10, 0);
		return theView;
	}

	public void onDataReady(Serviceworker worker, Object data) {
		super.onDataReady(worker, data);
		final Vector list = (Vector)data;
		if(worker.responseCode == 200){
			UiApplication.getUiApplication().invokeLater(new Runnable(){
				public void run(){
					bindKPI(list);
				}
			});
		}
	}
}
